import sys
import subprocess
import os
import datetime
import rich
# 关键修复：确保导入 QApplication（必须包含在QtWidgets导入列表中）
from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                               QTextEdit, QPushButton, QMessageBox, QLabel, QApplication)
from PySide6.QtCore import Slot,Qt


# -------------------------- 关键配置（请手动确认！） --------------------------
# 【务必修改】替换为你Edge的真实路径（参考之前的方法获取）
# 路径用 r 开头（原始字符串），避免转义字符问题
# EDGE_EXEC_PATH = r"C:\Program Files\Microsoft\Edge\Application\msedge.exe"  # 64位默认路径
EDGE_EXEC_PATH = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"  # 32位默认路径


# -------------------------- 路径检查函数（修复转义字符错误） --------------------------
def check_edge_path():
    if os.path.exists(EDGE_EXEC_PATH):
        print_with_time(f"✅ Edge路径验证通过：{EDGE_EXEC_PATH}")
        return True
    else:
        # 修复：用 r 原始字符串避免 \m 转义错误，或把 \ 换成 \\
        error_msg = r"❌ Edge路径不存在！\n你设置的路径：{}\n请按以下步骤修改：\n1. 打开Edge → 帮助和反馈 → 关于Edge\n2. 复制「安装位置」，在末尾加「\msedge.exe」\n3. 替换脚本中 EDGE_EXEC_PATH 的值".format(EDGE_EXEC_PATH)
        rich.print(f"[bold red][{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}][/bold red] {error_msg}")
        QMessageBox.critical(None, "致命错误：Edge路径无效", error_msg.replace(r"\n", "\n"))
        return False


# -------------------------- 工具函数 --------------------------
def print_with_time(*args, **kwargs) -> None:
    """带时间戳的日志输出"""
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)


def validate_urls(url_list: list) -> list:
    """验证网址有效性"""
    valid_urls = []
    for url in url_list:
        url = url.strip()
        if url and (url.startswith("http://") or url.startswith("https://")):
            valid_urls.append(url)
        elif url:
            print_with_time(f"[yellow]跳过无效网址[/yellow]：{url}（需以http://或https://开头）")
    return valid_urls


def open_url_with_edge(url: str) -> bool:
    """优化版：打开单个网址（解决路径空格、参数解析问题）"""
    try:
        cmd = [EDGE_EXEC_PATH, url]
        subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            creationflags=0x08000000,  # 隐藏命令行黑窗口
            shell=False
        )
        return True
    except FileNotFoundError:
        print_with_time(f"[red]启动失败[/red]：Edge程序未找到（路径错误）")
        return False
    except PermissionError:
        print_with_time(f"[red]启动失败[/red]：权限不足（请以管理员身份运行脚本）")
        return False
    except Exception as e:
        print_with_time(f"[red]启动失败[/red]：{str(e)}（可能被防火墙/安全软件阻止）")
        return False


# -------------------------- 测试函数 --------------------------
def test_single_url():
    """测试单个网址是否能启动"""
    test_url = "https://www.baidu.com"
    print_with_time(f"正在测试启动单个网址：{test_url}")
    if open_url_with_edge(test_url):
        print_with_time(f"[green]测试成功！[/green] 已尝试启动 {test_url}（请查看Edge是否打开）")
    else:
        print_with_time(f"[red]测试失败！[/red] 请按以下步骤排查：\n1. 确认EDGE_EXEC_PATH路径正确\n2. 以管理员身份运行脚本\n3. 关闭防火墙/安全软件")


# -------------------------- GUI窗口 --------------------------
class MiniUrlOpener(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("Edge批量开网址（最终修复版）")
        self.setFixedSize(550, 380)
        # self.setWindowFlags(self.windowFlags() & ~Qt.WindowMaximizeButtonHint)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(12)

        # 路径提示标签
        path_label = QLabel(f"当前Edge路径：\n{EDGE_EXEC_PATH}")
        path_label.setStyleSheet("font-size: 10px; color: #666;")
        main_layout.addWidget(path_label)

        # 网址输入框
        self.url_input = QTextEdit()
        self.url_input.setPlaceholderText("请输入网址（每行一个，示例：https://www.baidu.com）")
        self.url_input.setLineWrapMode(QTextEdit.NoWrap)
        self.url_input.setStyleSheet("font-size: 12px;")
        main_layout.addWidget(self.url_input, stretch=1)

        # 按钮区
        btn_layout = QHBoxLayout()
        # 测试启动按钮
        self.test_btn = QPushButton("测试启动百度")
        self.test_btn.setStyleSheet("padding: 6px 12px; background-color: #2196F3; color: white; border: none;")
        self.test_btn.clicked.connect(test_single_url)
        btn_layout.addWidget(self.test_btn)

        # 批量启动按钮
        self.start_btn = QPushButton("批量打开网址")
        self.start_btn.setStyleSheet("padding: 6px 12px; background-color: #4CAF50; color: white; border: none;")
        self.start_btn.clicked.connect(self.batch_open_urls)
        btn_layout.addWidget(self.start_btn)

        # 清空按钮
        self.clear_btn = QPushButton("清空输入")
        self.clear_btn.setStyleSheet("padding: 6px 12px;")
        self.clear_btn.clicked.connect(self.url_input.clear)
        btn_layout.addWidget(self.clear_btn)

        main_layout.addLayout(btn_layout)

    @Slot()
    def batch_open_urls(self):
        raw_text = self.url_input.toPlainText()
        if not raw_text.strip():
            QMessageBox.warning(self, "提示", "请先输入至少一个网址！")
            return

        all_urls = raw_text.splitlines()
        valid_urls = validate_urls(all_urls)
        if not valid_urls:
            QMessageBox.warning(self, "提示", "未检测到有效网址（需以http://或https://开头）")
            return

        print_with_time(f"开始批量启动 {len(valid_urls)} 个网址...")
        success_count = 0
        for idx, url in enumerate(valid_urls, 1):
            if open_url_with_edge(url):
                success_count += 1
                print_with_time(f"[{idx}/{len(valid_urls)}] 启动成功：{url}")

        result_msg = f"批量启动完成！\n总网址：{len(valid_urls)} 个\n成功：{success_count} 个\n失败：{len(valid_urls)-success_count} 个"
        QMessageBox.information(self, "结果", result_msg)
        print_with_time(result_msg)


# -------------------------- 程序入口 --------------------------
if __name__ == "__main__":
    # 修复：确保 QApplication 被正确调用（已在开头导入）
    app = QApplication(sys.argv)
    # app.setAttribute(Qt.AA_DisableHighDpiScaling, True)

    print_with_time("="*50)
    print_with_time("Edge批量开网址工具（最终修复版）启动")
    print_with_time("="*50)

    # 验证Edge路径
    if not check_edge_path():
        sys.exit(1)

    # 显示窗口
    window = MiniUrlOpener()
    window.show()

    sys.exit(app.exec())